package nl.saxion.security.serverconfig;

import javax.crypto.SealedObject;

import com.google.inject.Inject;
import com.google.inject.name.Named;

import nl.saxion.security.config.Config;
import nl.saxion.security.config.INIConfig;
import nl.saxion.security.encryption.TransformerAES;
import nl.saxion.security.synchronize.ServerSynchronize;

/**
 * Singleton class to handle the serversynchronize
 * @author Martijn
 *
 */
public class ServerConfig {
	private ServerSynchronize serverSynchronize;
	private static ServerConfig ref;
	private Config config;
	private TransformerAES transformer;

	
	public ServerConfig(Config aConfig) {
		config = aConfig;
		transformer = new TransformerAES();
	}

	public static ServerConfig getSingletonObject(Config aConfig) {
		if (ref == null)
			// it's ok, we can call this constructor
			ref = new ServerConfig(aConfig);
		return ref;
	}

	public Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
		// Not possible
	}

	public void setUpServer() {
		try {
			if (serverSynchronize == null) {
				String dir = config.getAsString(Config.KEY_SYNC_PATH, "C:/");
				String pass = config.getAsString(Config.KEY_SYNC_ENCR_PASS,
						"falsekey");
				String key = config.getAsString(Config.KEY_SYNC_ENCR_KEY,
						"falsekey");
				byte[] passbyte = transformer.hexStringToByteArray(pass);
				SealedObject sObject = transformer.encryptObject(passbyte, key);

				serverSynchronize = new ServerSynchronize(dir, null, passbyte);
				serverSynchronize.start();
				System.out.println("Server Running");
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void startserverSync() {
		serverSynchronize.enableSync();
	}

	public void changePassword() {
		if (serverSynchronize != null) {
			String pass = config.getAsString(Config.KEY_SYNC_ENCR_PASS,
					"falsekey");
			byte[] passbyte = transformer.hexStringToByteArray(pass);
			System.out.println("changed Server Settings");
			serverSynchronize.setPassword(passbyte);
		}
	}

	public void changeDirectory() {
		if (serverSynchronize != null) {
			String dir = config.getAsString(Config.KEY_SYNC_PATH, "F:/");
			System.out.println("changed Server Settings");
			serverSynchronize.setDirectory(dir);
		}
	}

}
